<?php

namespace App\Http\Controllers\QH_Api;

use App\Events\UserLearnVideoChangeEvent;
use App\Http\Controllers\TK_Api\ApiBaseController;
use App\Http\Requests\QH\LearnVideoPlayDurationUpdateRequest;
use App\Models\LearnVideo;
use App\Models\LearnVideoChapter;
use App\Models\LearnVideoSection;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\Types\Context;
use Psr\SimpleCache\InvalidArgumentException;

class LearnVideoController extends ApiBaseController
{

    /**
     * 获取视频详情
     * @return JsonResponse|object
     * @throws Exception
     */
    public function getLearnVideoInfo()
    {
        $id = request('id');
        if (empty($id)) throw new Exception('课程已下架');
        $model = LearnVideo::find($id);
        if (empty($model) || $model->is_active != 1) throw new Exception('课程已下架');

        //$model->log = DB::table('user_learn_video_logs')
        //    ->where('learnVideoId', $id)
        //    ->where('userId', $this->user->id)
        //    ->first();
        //if ($model->log && $model->log->expireAt) $model->log->expireAt = Carbon::make($model->log->expireAt)->format('Y-m-d');
        //if ($model->log && $model->log->lastWatchLearnVideoSectionId) {
        //    $model->log->lastWatchSection = LearnVideoSection::find($model->log->lastWatchLearnVideoSectionId);
        //}

        return $this->restful($model);
    }

    /**
     * @throws Exception
     */
    public function getLearnVideoChapters()
    {
        $id = request('id');
        if (empty($id)) throw new Exception('课程已下架');
        $chapters = LearnVideoChapter::where('learn_video_id', $id)
            ->with(['learnVideoSection' => function ($q) {
                $q->orderBy('sort');
            }])
            ->get();

        // 赋予播放进度
        $log = null;
        if ($this->user) {
            $log = DB::table('user_learn_video_logs')
                ->where('learnVideoId', $id)
                ->where('userId', $this->user->id)
                ->first();
        }
        foreach ($chapters as $chapter) {
            foreach ($chapter->learnVideoSection as $section) {
                $_find = false;
                if ($log) {
                    $logData = $log->data ? json_decode($log->data, true) : [];
                    foreach ($logData as $datum) {
                        if ($datum['chapterId'] == $chapter->id) {
                            foreach ($datum['sections'] as $_section) {
                                if ($_section['sectionId'] == $section->id) {
                                    $section->timer = $_section['duration'];
                                    $section->rate = min(round($_section['rate'] * 100), 100);
                                    $section->firstWatch = $_section['firstWatch'];
                                    $section->lastWatch = $_section['lastWatch'];
                                    $_find = true;
                                }
                            }
                        }
                    }
                }

                if (!$_find) {
                    $section->timer = 0;
                    $section->rate = 0;
                    $section->firstWatch = time();
                    $section->lastWatch = time();
                }
            }
        }

        return $this->restful($chapters);
    }

    /**
     * 保存播放进度
     * @param LearnVideoPlayDurationUpdateRequest $request
     * @return JsonResponse|object
     * @throws InvalidArgumentException
     */
    public function savePlayDuration(LearnVideoPlayDurationUpdateRequest $request)
    {
        $params = $request->validated();

        $model = LearnVideoSection::find($params['learnVideoSectionId']);
        if($model) {
            $log = DB::table('user_learn_video_logs')
                ->where('userId', $this->user->id)
                ->where('learnVideoId', $model->learn_video_id)
                ->first();

            $logData = [];
            if ($log && $log->data) $logData = json_decode($log->data, true);
            $logData = array_values($logData);

            $dataRes = updateUserLearnVideoLogData($logData, $model, $params['duration']);

            // 统计：今日学习时长、累计时长、学习天数、完成课程数
            if (!$this->user->netCourseLearnOfLastTime) $this->user->netCourseLearnOfLastTime = now()->subHours(25);
            $netCourseLearnOfLastTimeOfToday = \Cache::get('netCourseLearnOfLastTime_user'.$this->user->id);

            if (!$this->user->netCourseLearnOfLastTime || ($this->user->netCourseLearnOfLastTime && !Carbon::make($this->user->netCourseLearnOfLastTime)->isToday())) {
                $this->user->netCourseLearnMinuteOfToday = 0;
            }
            // 学习时长就是上次记录的时间差，但是时间差必须小于等于30分钟
            $learnDiffMinutes = Carbon::createFromTimestamp($netCourseLearnOfLastTimeOfToday)->diffInMinutes(now());

            if ($netCourseLearnOfLastTimeOfToday || !Carbon::make($this->user->netCourseLearnOfLastTime)->isToday()) {
                $netCourseLearnOfLastTimeOfToday = time();
            }
            \Cache::set('netCourseLearnOfLastTime_user'.$this->user->id, $netCourseLearnOfLastTimeOfToday, now()->diffInSeconds(now()->endOfDay()));
            if ($learnDiffMinutes <= 30) {
                $this->user->netCourseLearnMinute += $learnDiffMinutes;
                $this->user->netCourseLearnMinuteOfToday += $learnDiffMinutes;
            }

            // 用户已学section count
            $this->user->learnVideoSectionDoneCount = DB::table('user_learn_video_logs')
                ->where('userId', $this->user->id)->sum('watchSectionCount') ?? 0;

            // 用户最后学习时间
            $this->user->netCourseLearnOfLastTime = now();

            $this->user->save();

            DB::table('user_learn_video_logs')->updateOrInsert([
                'userId' => $this->user->id,
                'learnVideoId' => $model->learn_video_id
            ], [
                'data' => json_encode(array_values($dataRes['data'])),
                'watchSectionCount' => $dataRes['sectionCount'],
                'lastWatchLearnVideoSectionId' => $params['learnVideoSectionId']
            ]);
            event(new UserLearnVideoChangeEvent($this->user->id));
        }

        return $this->restful();
    }

    /**
     * 获取用户的课程
     * @return JsonResponse|object
     */
    public function getMyLearnVideo()
    {
        $learnVideoLogs = DB::table('user_learn_video_logs')->where('userId', $this->user->id)->orderByDesc('id')->get();

        $freeIds = [];
        $buyIds = [];
        foreach ($learnVideoLogs as $learnVideoLog) {
            if ($learnVideoLog->isTry == 1) {
                $freeIds[] = $learnVideoLog->learnVideoId;
            }else {
                if (\Illuminate\Support\Carbon::make($learnVideoLog->expireAt??now()->subMinutes(10))->lt(now())) {
                    continue;
                }
                $buyIds[] = $learnVideoLog->learnVideoId;
            }
        }

        // 需要分类
        $list['free'] = LearnVideo::whereIn('id', $freeIds)
            ->where('is_active', 1)
            ->get();

        $list['buy'] = LearnVideo::whereIn('id', $buyIds)
            ->where('is_active', 1)
            ->get();

        return $this->restful($list);
    }

    public function getMyLearnVideoBuyLog()
    {
        $list = LearnVideo::select([
            'learn_videos.*',
            'user_learn_video_logs.userId',
            'user_learn_video_logs.getAt',
            'user_learn_video_logs.getType',
            'user_learn_video_logs.isTry',
            'user_learn_video_logs.expireAt',
        ])
            ->join('user_learn_video_logs', 'learn_videos.id', '=', 'user_learn_video_logs.learnVideoId')
            ->where('user_learn_video_logs.userId', $this->user->id)
            ->where('user_learn_video_logs.isTry', 0)
            ->orderByDesc('user_learn_video_logs.getAt')
            ->get();
        foreach ($list as $item) {
            if ($item->expireAt) {
                if (Carbon::make($item->expireAt)->diffInYears(now()) > 90) $item->expireAt2 = '长期';
                else $item->expireAt2 = Carbon::make($item->expireAt)->format('Y-m-d');
            }
        }

        return $this->restful($list);
    }
}
